import React, { useEffect, useReducer } from 'react';

// 1. 创建组件的初始状态
const initState = {
  bannerList: [],
  proList: []
}
// 2. 创建修改 state 事件的 reducer
const reducer = (state, action) => {
  switch (action.type) {
    case 'changeBannerList':
      // 返回一个新的状态
      return {...state, bannerList: action.payload}
    case 'changeProList':
      // 返回一个新的状态
      return {...state, proList: action.payload}
    default:
      return state
  }
}


const App = () => {
  // 使用 useReducer 的时候可以传递两个参数分别是修改函数和初始状态
  const [state, dispatch] = useReducer(reducer, initState)

  useEffect(()=>{
    fetch('http://121.89.205.189:3000/api/banner/list').then(res => res.json()).then(res => {
      console.log(res.data);
      dispatch({
        type: 'changeBannerList',
        payload: res.data
      })
    })
  }, [])

  // 发送数据请求将数据放在 proList 中
  useEffect(()=>{
    fetch('http://121.89.205.189:3000/api/pro/list').then(res => res.json()).then(res => {
      console.log(res.data);
      dispatch({
        type: 'changeProList',
        payload: res.data
      })
    })
  }, [])

  return (
    <div>
      {state.bannerList.length > 0 && state.bannerList.map(item => (<div key={item.bannerid}>
        <img src={item.img} style={{width: 100}} alt='' />
      </div>))}

      <ol>
        {state.proList && state.proList.map(item => (<li key={item.proid}>{item.proname}</li>))}
      </ol>

    </div>
  );
};

export default App;
